package com.example.managemyself.ui.settings;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.managemyself.R;
import com.example.managemyself.config.AppConfig;
import com.example.managemyself.data.network.WeatherApiService;
import com.example.managemyself.util.DeepSeekHelper;
import com.google.android.material.textfield.TextInputEditText;

/**
 * API配置管理Fragment
 */
public class ApiConfigFragment extends Fragment {
    
    private TextInputEditText editDeepSeekApiKey;
    private TextInputEditText editTianApiKey;
    private TextInputEditText editWeatherApiId;
    private TextInputEditText editWeatherApiKey;
    private Button btnSaveConfig;
    private Button btnTestDeepSeek;
    private Button btnTestWeather;
    private Button btnTestTianApi;
    
    private AppConfig appConfig;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_api_config, container, false);
        
        initViews(view);
        loadCurrentConfig();
        setupListeners();
        
        return view;
    }
    
    private void initViews(View view) {
        editDeepSeekApiKey = view.findViewById(R.id.edit_deepseek_api_key);
        editTianApiKey = view.findViewById(R.id.edit_tian_api_key);
        editWeatherApiId = view.findViewById(R.id.edit_weather_api_id);
        editWeatherApiKey = view.findViewById(R.id.edit_weather_api_key);
        btnSaveConfig = view.findViewById(R.id.btn_save_config);
        btnTestDeepSeek = view.findViewById(R.id.btn_test_deepseek);
        btnTestWeather = view.findViewById(R.id.btn_test_weather);
        btnTestTianApi = view.findViewById(R.id.btn_test_tian_api);
        
        appConfig = AppConfig.getInstance();
    }
    
    private void loadCurrentConfig() {
        // 加载当前配置
        String deepSeekKey = appConfig.getDeepSeekApiKey();
        String tianApiKey = appConfig.getTianApiKey();
        String weatherApiId = appConfig.getWeatherApiId();
        String weatherApiKey = appConfig.getWeatherApiKey();
        
        // 显示API密钥（部分隐藏）
        editDeepSeekApiKey.setText(maskApiKey(deepSeekKey));
        editTianApiKey.setText(maskApiKey(tianApiKey));
        editWeatherApiId.setText(weatherApiId);
        editWeatherApiKey.setText(weatherApiKey);
    }
    
    private void setupListeners() {
        btnSaveConfig.setOnClickListener(v -> saveConfiguration());
        btnTestDeepSeek.setOnClickListener(v -> testDeepSeekApi());
        btnTestWeather.setOnClickListener(v -> testWeatherApi());
        btnTestTianApi.setOnClickListener(v -> testTianApi());
    }
    
    private void saveConfiguration() {
        String deepSeekKey = editDeepSeekApiKey.getText() != null ? 
            editDeepSeekApiKey.getText().toString().trim() : "";
        String tianApiKey = editTianApiKey.getText() != null ? 
            editTianApiKey.getText().toString().trim() : "";
        String weatherApiId = editWeatherApiId.getText() != null ? 
            editWeatherApiId.getText().toString().trim() : "";
        String weatherApiKey = editWeatherApiKey.getText() != null ? 
            editWeatherApiKey.getText().toString().trim() : "";
        
        // 如果是掩码形式，则不更新
        if (!deepSeekKey.contains("*") && !deepSeekKey.isEmpty()) {
            appConfig.setString(AppConfig.DEEPSEEK_API_KEY, deepSeekKey);
        }
        if (!tianApiKey.contains("*") && !tianApiKey.isEmpty()) {
            appConfig.setString(AppConfig.TIANAPI_KEY, tianApiKey);
        }
        if (!weatherApiId.isEmpty()) {
            appConfig.setString(AppConfig.WEATHER_API_ID, weatherApiId);
        }
        if (!weatherApiKey.isEmpty()) {
            appConfig.setString(AppConfig.WEATHER_API_KEY, weatherApiKey);
        }
        
        Toast.makeText(getContext(), "API配置已保存", Toast.LENGTH_SHORT).show();
        
        // 重新加载配置显示
        loadCurrentConfig();
    }
    
    private void testDeepSeekApi() {
        btnTestDeepSeek.setEnabled(false);
        btnTestDeepSeek.setText("测试中...");
        
        DeepSeekHelper.getChatResponse("你好，请简单介绍一下你自己", new DeepSeekHelper.DeepSeekCallback() {
            @Override
            public void onResponse(String response) {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        btnTestDeepSeek.setEnabled(true);
                        btnTestDeepSeek.setText("测试DeepSeek");
                        Toast.makeText(getContext(), "DeepSeek API测试成功！", Toast.LENGTH_SHORT).show();
                    });
                }
            }
            
            @Override
            public void onError(String error) {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        btnTestDeepSeek.setEnabled(true);
                        btnTestDeepSeek.setText("测试DeepSeek");
                        Toast.makeText(getContext(), "DeepSeek API测试失败: " + error, Toast.LENGTH_LONG).show();
                    });
                }
            }
        });
    }
    
    private void testWeatherApi() {
        btnTestWeather.setEnabled(false);
        btnTestWeather.setText("测试中...");
        
        WeatherApiService.getInstance().getBeijingWeather(new WeatherApiService.WeatherCallback() {
            @Override
            public void onSuccess(WeatherApiService.WeatherInfo weatherInfo) {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        btnTestWeather.setEnabled(true);
                        btnTestWeather.setText("测试天气API");
                        Toast.makeText(getContext(), "天气API测试成功！\n" + 
                            weatherInfo.getPlace() + " " + weatherInfo.getTemperature(), 
                            Toast.LENGTH_SHORT).show();
                    });
                }
            }
            
            @Override
            public void onError(String error) {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        btnTestWeather.setEnabled(true);
                        btnTestWeather.setText("测试天气API");
                        Toast.makeText(getContext(), "天气API测试失败: " + error, Toast.LENGTH_LONG).show();
                    });
                }
            }
        });
    }
    
    private void testTianApi() {
        btnTestTianApi.setEnabled(false);
        btnTestTianApi.setText("测试中...");
        
        // 这里可以添加天行API的测试代码
        // 暂时模拟测试结果
        new Thread(() -> {
            try {
                Thread.sleep(2000); // 模拟网络请求
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        btnTestTianApi.setEnabled(true);
                        btnTestTianApi.setText("测试天行API");
                        
                        String tianApiKey = appConfig.getTianApiKey();
                        if (tianApiKey != null && !tianApiKey.isEmpty() && !tianApiKey.equals("your_tianapi_key")) {
                            Toast.makeText(getContext(), "天行API配置正常！", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getContext(), "天行API密钥未配置", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
    
    /**
     * 掩码显示API密钥
     */
    private String maskApiKey(String apiKey) {
        if (apiKey == null || apiKey.isEmpty() || apiKey.equals("your_api_key") || 
            apiKey.equals("your_tianapi_key") || apiKey.equals("your_deepseek_api_key")) {
            return "";
        }
        
        if (apiKey.length() <= 8) {
            return apiKey;
        }
        
        // 显示前4位和后4位，中间用*号代替
        String prefix = apiKey.substring(0, 4);
        String suffix = apiKey.substring(apiKey.length() - 4);
        int maskLength = Math.min(apiKey.length() - 8, 20); // 最多显示20个*
        StringBuilder mask = new StringBuilder();
        for (int i = 0; i < maskLength; i++) {
            mask.append("*");
        }
        
        return prefix + mask.toString() + suffix;
    }
} 